<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 2018/1/11
 * Time: 16:53
 */
namespace app\super\controller;

use think\Db;
use app\super\validate\AddUserValidate;
class ManagementController extends CommonController
{
    /**
     * getUserDate 查询用户表信息
     * @return $data 返回的多表查询数据
     */
    public function getUserDate()
    {
        $where['user_id'] = array('NEQ','0JipxUmFMaDL2o8tTOc2X5i9X8hwHa4p');
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        /*关键字*/
        if ($_POST['keyword'] != '') {
            $where['user_username|user_phone'] = $_POST['keyword'];
        }
        /*性别*/
        if ($_POST['sex'] != '') {
            $where['user_gender'] = $_POST['sex'];
        }
        /*是否启用*/
        if ($_POST['status'] != '') {
            $where['user_status'] = $_POST['status'];
        }

        /*注册时间*/
//        if ($_POST['start'] != '' || $_POST['end'] != ''){
//
//        }

        if($_POST['end']!='' && $_POST['start']!=''){
            $res = $this->betweenDate($where,$rows,$page,$_POST['start'],$_POST['end']);
        }else{
            if ($_POST['start'] != '') {//开始时间
                $where['user_time'] = array('>=', $_POST['start']);
            }
            if ($_POST['end'] != '') {//结束时间
                $where['user_time'] = array('<=', $_POST['end']);
            }
            $res = $this->Date($where,$rows,$page);
        }
        $total = $this->totalDate($where);

        $data['total'] = $total;
        $data['rows'] = $res;
        return json_encode($data);
    }

    /**
     * addUser 添加用户信息
     * @return 展示添加页面
     */
    public function addUser(){
        return $this->fetch('management/addUser');
    }

    /**
     * insert 添加用户信息进数据库
     * @return $returnData 返回状态
     */
    public function insert(){
        //validate 判断填写的信息是否符合要求
        $validata = new AddUserValidate();
        if(!$validata->check($_POST)){
            $returnData['status'] = 0;
            $returnData['msg'] = $validata->getError();
            return json_encode($returnData);
        }else{
            //查询手机号是否已被注册&手机号填写是否正确
            if(preg_match("/^1[34578]{1}\d{9}$/",$_POST['phone_num'])){
                $res = Db::table('up_u_admin')->where('user_phone',$_POST['phone_num'])->column('user_phone');
                if($res != null){
                    $returnData['status'] = 0;
                    $returnData['msg'] = "手机号已被注册！";
                    return json_encode($returnData);
                }
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "请填写正确的手机号码！";
                return json_encode($returnData);
            }
            //判断是否添加了头像
            if($_FILES['file']['name']=='') {
                $returnData['status'] = 0;
                $returnData['msg'] = "请为用户添加一个头像！";
                return json_encode($returnData);
            }

            //上传头像
            $rands = date('YmdHis').rand(100000,999999);
            $exes = explode('.',$_FILES['file']['name']);
            $filePaths = $_FILES['file']['tmp_name'];

            $infos = $this->qnCommon(2,$rands,$exes[1],$filePaths);
            if($infos['status']!=200) {
                $returnData['status'] = 0;
                $returnData['msg'] = "上传文件格式不正确";
                return json_encode($returnData);
            }

            //组装表单收集的用户信息
            $data['user_id'] = $this->getRandChar(32);
            $data['user_username'] =  $_POST['user_name'];
            $data['user_phone'] = $_POST['phone_num'];
            $data['user_image'] = QiNiu.$infos['key'];
            $data['user_signature'] = $_POST['user_introduction'];
            $data['user_gender'] = $_POST['sex'];
            $data['user_time'] = date('Y-m-d H:i:s');
            $data['user_status'] = 1;//直接启用
            $data['user_password']=md5('123456'.Yan);
            //用户信息存入数据库
            $res = Db::table('up_u_admin')->insert($data);
            if($res){
                return json_encode(array("status" => 1, "msg" => "添加成功！"));
            }else{
                return json_encode(array("status" => 0, "msg" => "添加失败！"));
            }
        }

    }

    /**
     * updateuser 修改用户信息
     * @return 展示修改页面
     */
    public function updateuser()
    {
        $cid = $_POST['nid'];
        $where['user_id'] = $cid;
        $res = Db::table('up_u_admin')
            ->where($where)
            ->field('user_id,user_phone,user_username,user_gender,user_image,user_signature,user_password,password')
            ->find();
//        var_dump($res);die;
        $this->assign('res',$res);
        return $this->fetch('management/updateuser');
    }

    /**
     * changeuser 修改用户信息
     * @return 修改数据存入数据库
     */
    public function changeuser(){
        $validata = new AddUserValidate();
        if(!$validata->check($_POST)){
            $returnData['status'] = 0;
            $returnData['msg'] = $validata->getError();
            return json_encode($returnData);
        }else{
            $where['user_id'] = $_POST['user_id'];
            //查询手机号是否已被注册&手机号填写是否正确
            if(preg_match("/^1[34578]{1}\d{9}$/",$_POST['phone_num'])){
                $arr = Db::table("up_u_admin")->where($where)->value('user_phone');
                if($arr!=$_POST['phone_num']){
                    $res = Db::table('up_u_admin')->where('user_phone',$_POST['phone_num'])->column('user_phone');
                    if($res != null){
                        $returnData['status'] = 0;
                        $returnData['msg'] = "手机号已被注册！";
                        return json_encode($returnData);
                    }
                }
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "请填写正确的手机号码！";
                return json_encode($returnData);
            }
            //上传头像
            if($_FILES['file']['name']!=='') {
                $rands = date('YmdHis').rand(100000,999999);
                $exes = explode('.',$_FILES['file']['name']);
                $filePaths = $_FILES['file']['tmp_name'];

                $infos = $this->qnCommon(2,$rands,$exes[1],$filePaths);
                if($infos['status']!=200) {
                    $returnData['status'] = 0;
                    $returnData['msg'] = "上传文件格式不正确";
                    return json_encode($returnData);
                }
                $data['user_image'] = QiNiu.$infos['key'];
            }
            //组装表单收集的用户信息
            $data['user_username'] =  $_POST['user_name'];
            $data['user_phone'] = $_POST['phone_num'];
            $data['user_signature'] = $_POST['user_introduction'];
            $data['user_gender'] = $_POST['sex'];
            $data['password'] = $_POST['user_password'];
            $data['user_password'] = md5($_POST['user_password'].Yan);
            $res = Db::table('up_u_admin')->where($where)->update($data);
            if($res){
                return json_encode(array("status" => 1, "msg" => "修改成功！"));
            }else{
                return json_encode(array("status" => 0, "msg" => "修改失败！"));
            }
        }

    }

    /**
     * disableduser 停用用户
     * @return 返回状态
     */
    public function disableduser(){
        $data = $this->oneuser($_POST['cid'],2,"已停用！","停用失败！");
        return $data;
    }

    /**
     * enableuser 启用用户
     * @return 返回状态
     */
    public function enableuser(){
        $data = $this->oneuser($_POST['cid'],1,"已启用！","启用失败！");
        return $data;
    }

    /**
     * enablealluser 启用所有用户
     * @return 返回状态
     */
    public function enablealluser(){
        $data = $this->alluser(1,2,"已启用所有用户！","启用失败！");
        return $data;
    }

    /**
     * disablealluser 停用所有用户
     * @return 返回状态
     */
    public function disablealluser(){
        $data = $this->alluser(2,1,"已停用所有用户！","停用失败！");
        return $data;
    }

    /**
     * alluser 停用或启用所有用户
     * @param $num & $D状态值、$succemsg成功返回信息、$failedmsg失败返回信息
     * @return 返回状态
     */
    protected function alluser($num,$D,$succemsg,$failedmsg){
        $data['user_status'] = $num;
        $arr = Db::table('up_u_admin')->where('user_status',$D)->select();
        if($arr != null ){
            $res =  Db::table('up_u_admin')->where("user_status",$D)->update($data);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = $succemsg;
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = $failedmsg;
            }
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = $succemsg;
        }

        return json_encode($returnData);
    }

    /**
     * alluser 停用或启用单个用户
     * @param、$uid用户id、$num状态值、$succemsg成功返回信息、$failedmsg失败返回信息
     * @return 返回状态
     */
    protected function oneuser($uid,$num,$succemsg,$failedmsg){
        if($uid!=''){
            $where['user_id'] = $uid;
            $data['user_status'] = $num;//停用|启用
            $res =  Db::table('up_u_admin')->where($where)->update($data);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = $succemsg;

            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = $failedmsg;
            }
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "传递参数错误";
        }
        return json_encode($returnData);
    }


    /**
     * usercontrol 用户权限
     * @return 展示页面
     */
    public function usercontrol(){
        $data = Db::table('up_menus')
            ->where('parent_menuid','=','1')
            ->where('id',['<>',1000],['<>',114],'and')
            ->where('status',1)
            ->field('id,menu_name,parent_menuid')
            ->select();
        $where['user_id'] = $_POST['cid'];
        $res = Db::table('up_u_admin')
            ->where($where)
            ->field('user_id,user_type')
            ->find();
        $info = explode(",",$res['user_type']);
//        var_dump($res['user_type']);die;
        $this->assign('res',$res);
        $this->assign('arr',$info);
        $this->assign('info',$data);
        return $this->fetch('management/permission');
    }

    /**
     * permissioninsert 用户权限插入数据库
     * @return 展示页面
     */
    public function permissioninsert(){
        if(isset($_POST['perm'])){
            $str = implode(',',$_POST['perm']);
            $data['user_type'] = $str;
            $res = Db::table('up_u_admin')->where('user_id',input('user_id'))->update($data);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "权限添加成功！";
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "权限添加失败！";
            }
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "用户至少有一个权限！";
        }
        return json_encode($returnData);
    }
    /**
     * Date 单时间区间查询用户表信息
     * @param $where 查询条件，$rows $page 分页数据。
     * @return $data 返回的多表查询数据
     */
    protected function Date($where,$rows,$page){
        $data = Db::table('up_u_admin')
            ->where($where)
            ->field('user_id,user_username,user_phone,user_gender,user_time,user_status')
            ->limit($rows * ($page - 1), $rows)
            ->order('user_time desc')
            ->select();
        return $data;
    }

    /**
     * betweenDate 时间区间查询用户表信息
     * @param $where 查询条件，$rows $page 分页数据 $s 起始时间 $e 结束时间。
     * @return $data 返回的多表查询数据
     */
    protected function betweenDate($where,$rows,$page,$s,$e){
        $data = Db::table('up_u_admin')
            ->where($where)
            ->whereTime('user_time','between',[$s,$e])
            ->field('user_id,user_username,user_phone,user_gender,user_time,user_status')
            ->limit($rows * ($page - 1), $rows)
            ->order('user_time desc')
            ->select();
        return $data;
    }

    /**
     * totalDate 查询用户表信息
     * @param $where 查询条件。
     * @return $data 返回的多表查询数据
     */
    protected  function totalDate($where){
        $data = Db::table('up_u_admin')
            ->where($where)
            ->count();
        return $data;
    }
}